﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace Se.Thread
{
    /// <summary>
    /// 线程队列
    /// </summary>
    public class ThreadQueue
    {
        private System.Collections.Concurrent.ConcurrentQueue<Action> _actionQueue;

        private int isWorking;

        public ThreadQueue()
        {
            this._actionQueue = new System.Collections.Concurrent.ConcurrentQueue<Action>();
            isWorking = 0;
        }

        /// <summary>
        /// 加入到线程队列
        /// </summary>
        /// <param name="action"></param>
        public void Enqueue(Action action)
        {
            this._actionQueue.Enqueue(action);
            if (Interlocked.CompareExchange(ref this.isWorking, 1, 0) == 0)
            {
                ThreadPool.QueueUserWorkItem(TryDequeueAction);
            }
        }

        private void TryDequeueAction(object state)
        {
            Action action;
            this._actionQueue.TryDequeue(out action);
            if (action != null)
            {
                action();
                TryDequeueAction(state);
                return;
            }
            Interlocked.Exchange(ref this.isWorking, 0);
        }
    }
}
